const Account = require("../models/accountModel");

// CREATE Account
exports.createAccount = async (req, res) => {
  try {
    const { parentAccount, accountNumber, accountName, openingBalance, note } = req.body;

    if (!accountNumber || !accountName) {
      return res
        .status(400)
        .json({ success: false, message: "Account Number and Account Name are required" });
    }

    if (parentAccount) {
      const parent = await Account.findById(parentAccount);
      if (!parent) {
        return res
          .status(400)
          .json({ success: false, message: "Invalid parent account" });
      }
    }

    const newAccount = new Account({
      parentAccount: parentAccount || null,
      accountNumber,
      accountName,
      openingBalance: openingBalance || 0,
      note: note || "",
      createdBy: req.user ? req.user.id : null,
      createdByModel: req.user ? (req.user.role.toLowerCase() === "admin" ? "Admin" : "User") : "User",
    });
    

    const savedAccount = await newAccount.save();
    return res
      .status(201)
      .json({ success: true, message: "Account created successfully", data: savedAccount });
  } catch (error) {
    console.error("Error creating account:", error);
    return res.status(500).json({ success: false, message: error.message });
  }
};

// GET all Accounts with creatorName populated
exports.getAllAccounts = async (req, res) => {
  try {
    const accounts = await Account.find()
      .populate("parentAccount", "accountName accountNumber")
      .populate("createdBy", "name FirstName LastName"); // populate createdBy if available

    // Compute creatorName for each account
    const processedAccounts = accounts.map((account) => {
      let creatorName = "";
      if (account.createdBy) {
        if (account.createdBy.name) {
          creatorName = account.createdBy.name;
        } else if (account.createdBy.FirstName && account.createdBy.LastName) {
          creatorName = `${account.createdBy.FirstName} ${account.createdBy.LastName}`;
        }
      }
      return { ...account.toObject(), creatorName };
    });

    return res.status(200).json({ success: true, data: processedAccounts });
  } catch (error) {
    console.error("Error fetching accounts:", error);
    return res.status(500).json({ success: false, message: error.message });
  }
};

// GET single Account by ID with creatorName populated
exports.getAccountById = async (req, res) => {
  try {
    const account = await Account.findById(req.params.id)
      .populate("parentAccount", "accountName accountNumber")
      .populate("createdBy", "name FirstName LastName"); // populate createdBy if available

    if (!account) {
      return res.status(404).json({ success: false, message: "Account not found" });
    }

    let creatorName = "";
    if (account.createdBy) {
      if (account.createdBy.name) {
        creatorName = account.createdBy.name;
      } else if (account.createdBy.FirstName && account.createdBy.LastName) {
        creatorName = `${account.createdBy.FirstName} ${account.createdBy.LastName}`;
      }
    }

    return res.status(200).json({ success: true, data: { ...account.toObject(), creatorName } });
  } catch (error) {
    console.error("Error fetching account:", error);
    return res.status(500).json({ success: false, message: error.message });
  }
};

// UPDATE Account
exports.updateAccount = async (req, res) => {
  try {
    const { id } = req.params;
    const { parentAccount, accountNumber, accountName, openingBalance, note, status } = req.body;

    if (parentAccount) {
      const parent = await Account.findById(parentAccount);
      if (!parent) {
        return res.status(400).json({ success: false, message: "Invalid parent account" });
      }
    }

    const updated = await Account.findByIdAndUpdate(
      id,
      { parentAccount, accountNumber, accountName, openingBalance, note, status },
      { new: true }
    );

    if (!updated) {
      return res.status(404).json({ success: false, message: "Account not found" });
    }
    return res
      .status(200)
      .json({ success: true, message: "Account updated successfully", data: updated });
  } catch (error) {
    console.error("Error updating account:", error);
    return res.status(500).json({ success: false, message: error.message });
  }
};

// DELETE Account
exports.deleteAccount = async (req, res) => {
  try {
    const deleted = await Account.findByIdAndDelete(req.params.id);
    if (!deleted) {
      return res.status(404).json({ success: false, message: "Account not found" });
    }
    return res.status(200).json({ success: true, message: "Account deleted successfully" });
  } catch (error) {
    console.error("Error deleting account:", error);
    return res.status(500).json({ success: false, message: error.message });
  }
};
